#coding=utf-8
from uliweb import expose

@expose('/group')
def group():
    from models import Group
    
    groups = Group.all().order_by(Group.c.create_time)
    return {'groups':groups}

@expose('/group/create')
def group_create():
    from forms import GroupCreateForm
    from models import create_group
    
    form = GroupCreateForm()
    if request.method == 'GET':
        return {'form':form}
    else:
        flag = form.validate(request.params)
        if flag:
            group = create_group(form.name.data, form.caption.data, form.description.data, form.managers.data)
            return redirect('/group/%s' % group.name)
        else:
            return {'form':form}
        
@expose('/group/<group_name>')
def group_view(group_name):
    from models import find_group
    group = find_group(group_name)
    return {'group':group}

@expose('/group/<group_name>/delete')
def group_delete(group_name):
    from models import delete_group
    delete_group(group_name, request.user)
    return redirect('/group')
    
@expose('/group/<group_name>/edit')
def group_edit(group_name):
    from forms import GroupEditForm
    from models import find_group
    from models import edit_group
    group = find_group(group_name)
    
    managers = [x.username for x in group.managers.all()]
    form = GroupEditForm(data={'name':group.name, 'caption':group.caption, 'description':group.description, 'managers':managers})
    if request.method == 'GET':
        return {'form':form, 'group':group}
    else:
        flag = form.validate(request.params)
        if flag:
            edit_group(group, form.description.data, form.managers.data, user=request.user)
            flash('Group successfully updated!') 
            return redirect('/group/%s/edit' % group.name)
        else:
            return {'form':form, 'group':group}

@expose('/group/<group_name>/join')
def group_join(group_name):
    from models import join_group
    if join_group(group_name, request.user):
        flash("You've already joined the group.")
    return redirect("/group/%s" % group_name)
    
@expose('/group/<group_name>/leave')
def group_leave(group_name):
    from models import leave_group
    if leave_group(group_name, request.user):
        flash("You've already leave the group.")
    return redirect("/group/%s" % group_name)
    
